// src/router/index.ts
import { createRouter, createWebHistory, RouteRecordRaw } from 'vue-router'
import HomeView from '../views/HomeView.vue'
import FoodDetail from '@/views/FoodDetail.vue'
import { foodData } from '@/data/foodData'
import AboutView from '@/views/AboutView.vue'
import LegalView from '@/views/LegalView.vue'
import ContactView from '@/views/ContactView.vue'
import PantryView from '@/views/PantryView.vue'

const routes: Array<RouteRecordRaw> = [
  {
    path: '/',
    name: 'home',
    component: HomeView
  },
  {
    path: '/the-pantry',
    name: 'pantry',
    component: PantryView,
    meta: { title: 'The Pantry' }
  },
  {
    path: '/about',
    name: 'about',
    component: AboutView,
    meta: { title: 'About Us' }
  },
  {
    path: '/legal',
    name: 'legal',
    component: LegalView,
    meta: { title: 'Legal Information' }
  },
  {
    path: '/contact',
    name: 'contact',
    component: ContactView,
    meta: { title: 'Contact Us' }
  },
  {
    path: '/food/:slug',
    name: 'FoodDetail',
    component: FoodDetail,
    props: true // 允许将路由参数作为组件的 props
  }
]

const router = createRouter({
  history: createWebHistory(process.env.BASE_URL),
  routes
})

// 路由钩子来动态设置标题
router.afterEach((to) => {
  if (to.name === 'FoodDetail') {
    const foodItem = foodData.find(food => food.slug === to.params.slug)
    if (foodItem) {
      document.title = foodItem.browserTitle // 使用 browserTitle 设置文档标题
    } else {
      document.title = 'Urban Plate' // 如果没有匹配项，则设置默认标题
    }
  } else if (to.name === 'home') {
    document.title = 'Urban Plate' // 设置主页的标题
  } else {
    document.title = 'Urban Plate' // 对于其他页面，设置默认标题
  }
})

export default router
